let db = require("../db/db")
let ddl_handler = require("./custom/ddl_handler")

ddl_handler.set_db(db);

let handle = async function (action, data, login_info, req, res) {
	switch (action) {
		case "quickbuild":
			//console.log(data);
			let trans = await db.transaction(multi = true);
			try {
				//检查表名是否存在，列名是否有重复，有空列名
				let sql="SELECT table_name as ct FROM information_schema.TABLES WHERE table_schema in (select database()) and table_name =?";
				let result=await trans.query(sql, [data.tablename]);
				if(result.rows.length>0){
					throw {name:"检查提交数据错误", message:"已经存在表: "+data.tablename};
				}
				if(data.fields.length==0){
					throw {name:"检查提交数据错误", message:"没有设置字段。"};
				}
				for (let field of data.fields) {
					let find=data.fields.filter(f=>f.field_name==field.field_name);
					if(find && find.length>1){
						throw {name:"检查提交数据错误", message:"重复的字段名: "+field.field_name};
					}
					if(!field.field_name){
						throw {name:"检查提交数据错误", message:"字段名为空: "+let.name};
					}
				}
				//创建逻辑
				let config_fields = [];
				let property_columns = [];
				for (let i in data.fields) {
					let f = data.fields[i];
					let type = "varchar";
					if (["date", "datetime"].includes(f.type)) {
						type = f.type;
					}
					else if (["config", "textarea"].includes(f.type)) {
						type = "long-text";
					}
					let config_field = {
						"id": i + 1,
						"name": f.field_name,
						"label": f.name,
						"required": f.required,
						"length": f.field_length,
						"type": type
					}
					let property_column = {
						"name": f.field_name,
						"label": f.name,
						"add_form_group": f.group_no,
						"searchable": true,
						"sortable": true,
						"quickedit": true
					}
					if (["number", "textarea", "date", "datetime", "switch"].includes(f.type)) {
						property_column.type = f.type;
					}
					else if (f.type == "file") {
						config_field.length = 100;
						property_column.type = "file";
					}
					else if (f.type == "image") {
						config_field.length = 100;
						property_column.type = "image";
					}
					else if (f.type == "radios") {
						property_column.type = "radios";
						property_column.options = f.options;
					}
					else if (f.type == "checkboxes") {
						property_column.type = "checkboxes";
						property_column.options = f.options;
					}
					else if (f.type == "config") {
						property_column.type = "config";
						property_column.options = f.options;
					}
					if (f.type == "select") {
						property_column.type = "select";
						config_field.select = { group: f.group_name };
					}
					else if (f.type == "related") {
						config_field.related = {
							"datamodel": f.related_datamodel,
							"model_table_name": f.related_table,
							"that_field": f.that_field,
							"that_label_field": f.that_label_field,
							"label": f.name
						}
						if (f.select_type == "select") {
							property_column.related = {
								"select_type": "select",
								"tree_select": [
									{
										"label": f.name,
										"label_field": f.that_label_field,
										"table_name": f.related_table,
										"this_field": f.that_field
									}
								]
							}
						}
						else if (f.select_type == "picker") {
							property_column.related = {
								"select_type": "picker",
								"datamodel": f.related_datamodel
							}
						}
					}
					config_fields.push(config_field)
					property_columns.push(property_column)
				}
				//数据模型
				let datamodel_params = {
					module: data.module,
					name: data.model_name,
					tablename: data.tablename,
					desc: data.desc,
					config: JSON.stringify({
						fields: config_fields
					}),
					create_user: login_info.user_id
				}
				sql = "insert into sys_datamodel set ?";
				let r = await trans.add(sql, datamodel_params);
				let model_id = r.results.insertId;
				//数据权限表
				result = await ddl_handler.add_data_funcs(model_id, login_info, req, res);
				let data_func_read_id = result.results[0].insertId;
				let data_func_add_id = result.results[1].insertId;
				let data_func_update_id = result.results[2].insertId;
				let data_func_del_id = result.results[3].insertId;
				//页面
				let page_params = {
					module: data.module,
					name: data.model_name + "管理",
					page_type_id: 1,
					desc: data.desc,
					property: JSON.stringify({
						"datamodel": model_id,
						"model_table_name": data.tablename,
						"columns": property_columns
					}),
					create_user: login_info.user_id
				}
				sql = "insert into sys_page set ?";
				r = await trans.add(sql, page_params);
				//功能权限
				let page_id = r.results.insertId;
				result = await ddl_handler.add_functions(page_id, 1, login_info, req, res);
				let func_id = result.results.insertId;
				//赋权
				sql = "";
				let role_params = [];
				for (let role_id of data.roles.split(",")) {
					sql += "insert into sys_role_func_r set ? ; \
									insert into sys_role_data_func_r set ? ; insert into sys_role_data_func_r set ? ;\
									insert into sys_role_data_func_r set ? ; insert into sys_role_data_func_r set ? ;";
					role_params.push({
						role_id: role_id,
						func_id: func_id
					});
					role_params.push({
						role_id: role_id,
						data_func_id: data_func_read_id
					});
					role_params.push({
						role_id: role_id,
						data_func_id: data_func_add_id
					});
					role_params.push({
						role_id: role_id,
						data_func_id: data_func_update_id
					});
					role_params.push({
						role_id: role_id,
						data_func_id: data_func_del_id
					});
				}
				await trans.add(sql, role_params);
				//菜单
				let menu_params = {
					name: data.model_name,
					icon: "fa-paper-plane",
					parent_id: data.parent_menu,
					page_id: page_id,
					create_user: login_info.user_id
				}
				sql = "insert into sys_menu set ?";
				r = await trans.add(sql, menu_params);
				let menu_id = r.results.insertId;
				//提交全部事务
				await trans.commit();
				//数据库表最后加，因为ddl不能rollback
				await ddl_handler.ddl_add_table(data.tablename, JSON.parse(datamodel_params.config));
				console.log("CRUD quick built successfully!");
				return ({ model_id: model_id, page_id: page_id, menu_id: menu_id });
			}
			catch (err) {
				trans.rollback();
				throw (err);
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };